import request from "@/axios/request";
import request2 from "@/axios/request2";

const {ElMessage} = require("element-plus");

export default {
    name: "LandlordHouse",
    data() {
        return {
            loading: true,
            dialogVisible1: false,
            dialogVisible2: false,
            landlordId: null,
            username: "",
            password: "",
            phone: "",
            email: "",
            total: 0,
            houseId: null,
            landlordId: null,
            title: "",
            address: "",
            description: "",
            price: null,
            area: "",
            size: null,
            roomCount: null,
            floor: null,
            imageUrl: "",
            fileList1: [],
            fileList2: [],
            status: "",
            form1: {
                houseId: null,
                landlordId: null,
                title: "",
                address: "",
                description: "",
                price: null,
                area: "",
                size: null,
                roomCount: null,
                floor: null,
                imageUrl: "",
                status: ""
            },
            form2: {
                title: "",
                address: "",
                description: "",
                price: null,
                area: "",
                size: null,
                roomCount: null,
                floor: null,
                imageUrl: "",
                landlordId: null,
                fileList: ""
            },
            allData: [], 
            // allData: [{
            //     houseId: 1,
            //     title: "学院十一峯",
            //     description: "学院十一峯位于温州市鹿城区滨江街道会展路与学院路交汇处，由金地集团与新希望地产联合开发，2021年竣工交付。项目总户数1276户，包含11栋板塔结合建筑，绿化率30%，容积率3.13，物业费4.7元/㎡·月（含能耗费）。小区定位改善型住宅，主力户型为143-189㎡的四居室，南北通透设计，精装修交付。‌‌",
            //     price: 5000,
            //     address: "温州市鹿城区滨江街道会展路与学院路交汇处",
            //     area: "浙江省",
            //     size: 140,
            //     roomCount: 3,
            //     floor: 3,
            //     landlordId: 1,
            //     status: "pending",
            //     imageUrl: "https://img2.baidu.com/it/u=668963934,1194070255&fm=253&fmt=auto&app=138&f=JPEG?w=661&h=500"
            // },
            // {
            //     houseId: 1,
            //     title: "学院十一峯",
            //     description: "学院十一峯位于温州市鹿城区滨江街道会展路与学院路交汇处，由金地集团与新希望地产联合开发，2021年竣工交付。项目总户数1276户，包含11栋板塔结合建筑，绿化率30%，容积率3.13，物业费4.7元/㎡·月（含能耗费）。小区定位改善型住宅，主力户型为143-189㎡的四居室，南北通透设计，精装修交付。‌‌",
            //     price: 5000,
            //     address: "温州市鹿城区滨江街道会展路与学院路交汇处",
            //     area: "浙江省",
            //     size: 140,
            //     roomCount: 3,
            //     floor: 3,
            //     landlordId: 1,
            //     status: "rented",
            //     imageUrl: "https://img2.baidu.com/it/u=668963934,1194070255&fm=253&fmt=auto&app=138&f=JPEG?w=661&h=500"
            // }],
            display: { display: 'none' },
            disabled: false,   
            available: true,
            rented: true,
            pending: true,
            rejected: true,
            filteredData: [],
            activeIndex: '/LandlordHouse',
            // fileList: [],
            // file_flag: 0,
        };
    },
    watch: {
        available: {
            handler() {
                this.filterData();
            }
        },
        rented: {
            handler() {
                this.filterData();
            }
        },
        pending: {
            handler() {
                this.filterData();
            }
        },
        rejected: {
            handler() {
                this.filterData();
            }
        }
    },
    created() {
        this.fetchUserInfo();
        this.load();
        this.loading = true;
        setTimeout(() => {
            this.loading = false;
        }, 1000);
        this.$nextTick(() => {
            this.filterData();
        });
    },
    methods: {
        async load() {
            try{
                let token = JSON.parse(window.sessionStorage.getItem('userInfo'));
                const landlordId = token.landlordId;
                const res = await request.get(`/house/landlord/${landlordId}`);
                if (res.code === 200) {
                    this.allData = res.data || [];
                    this.filteredData = this.allData;
                    this.filterData();
                    this.total = this.allData.length;
                } else {
                    ElMessage.error(res.msg || "加载失败");
                    this.allData = [];
                    this.total = 0;
                }
                this.loading = false;
            } catch (err){
                console.error(err);
                ElMessage.error("网络错误，请稍后再试");
                this.allData = [];
                this.total = 0; 
                this.loading = false;
            }
        },
        async fetchUserInfo() {
            let token = JSON.parse(window.sessionStorage.getItem('userInfo'));
            const landlordId = token.landlordId;
            const res = await request.get(`/landlord/findById/${landlordId}`);
            if (res.code === 200) {
                token=res.data;
            } else {
                ElMessage.error("获取用户信息失败");
            }
            console.log(token);
            if(!token) {
                ElMessage.error("获取用户信息失败");
                console.log("获取用户信息失败");
                return;
            }
            this.landlordId = token.landlordId;
            this.username = token.username;
            this.password = token.password;
            this.phone = token.phone;
            this.email = token.email;
    
            console.log(token);
        },
        filterData() {
            this.filteredData = this.allData.filter(item => {
                if (item.status === 'available' && this.available) return true;
                if (item.status === 'rented' && this.rented) return true;
                if (item.status === 'pending' && this.pending) return true;
                if (item.status === 'rejected' && this.rejected) return true;
                return false;
            });
            this.load();
        },
        SignOut() {
            sessionStorage.clear()
            ElMessage({
                message: '用户退出登录',
                type: 'success',
            });
            this.$router.replace({path: '/Login'});
        },
        // 获取标签类型
        getStatusTagType(status) {
            switch (status) {
                case 'pending': return 'warning'; 
                case 'available': return 'success';
                case 'rejected': return 'danger'; 
                case 'rented': return 'info';
                default: return '';
            }
        },
        // 获取状态文本
        getStatusLabel(status) {
            switch (status) {
                case 'pending': return '待审核';
                case 'available': return '上线中';
                case 'rejected': return '被拒绝';
                case 'rented': return '已出租';
                default: return '未知状态';
            }
        },
        handleEdit(row) {
            if (row.status !== 'pending') {
                ElMessage.error("已上线的房屋不能修改");
                return;
            }else{
                this.form1.houseId = row.houseId;
                this.form1.landlordId = row.landlordId;
                this.form1.title = row.title,
                this.form1.description = row.description,
                this.form1.price = row.price,
                this.form1.address = row.address,
                this.form1.area = row.area,
                this.form1.size = row.size,
                this.form1.roomCount = row.roomCount,
                this.form1.floor = row.floor,
                this.form1.status = "pending",
                this.form1.imageUrl = row.imageUrl,
                
                this.houseId = row.houseId;
                this.landlordId = row.landlordId;
                this.title = row.title,
                this.description = row.description,
                this.price = row.price,
                this.address = row.address,
                this.area = row.area,
                this.size = row.size,
                this.roomCount = row.roomCount,
                this.floor = row.floor,
                this.status = row.status,
                this.imageUrl = row.imageUrl,

                this.fileList1 = [{
                    name: 'current-image',
                    url: row.imageUrl
                }];

                this.dialogVisible1 = true;
            }
        },
        async handleDelete(row) {
            if (row.status === 'rented') {
                ElMessage.error("已出租的房屋记录不能被删除");
                return;
            }else{
                //删除
                request.delete(`/house/delete/${row.houseId}`).then((res) => {
                    if (res.code === 200) {
                        ElMessage({
                            message: "删除成功",
                            type: "success",
                        });
                        this.load();
                    } else {
                        ElMessage({
                            message: res.msg,
                            type: "error",
                        });
                    }
                });
            }
        },
        cancel1() {
            this.resetForm1();
            this.dialogVisible1 = false;
        },
        cancel2() {
            this.resetForm2();
            this.dialogVisible2 = false;
        },
        save1() {
            request.put('/house/update', this.form1)
            .then(response => {
                const code = response.code;
                if (code === 200) {
                    alert('更新成功');
                    this.fetchUserInfo();
                    this.load();
                } else {
                    alert(response.msg || '更新失败，请重试');
                }
            })
            .catch(err => {
                console.error('请求出错:', err);
                alert('更新失败，请重试');
            });
    
            console.log('提交数据:', this.form1);
    
            this.resetForm1();
            this.dialogVisible1 = false;


        },
        async save2() {
            let token = JSON.parse(window.sessionStorage.getItem('userInfo'));
            const landlordId = token.landlordId;
            this.form2.landlordId = landlordId;
            
            if (this.form2.fileList) {
                if (this.selectedFile) {
                    const formData = new FormData();
                    formData.append('file', this.selectedFile);
                    
                    try {
                        const uploadResponse = await request2.post('/house/upload', formData, {
                            headers: {
                                'Content-Type': 'multipart/form-data'
                            }
                        });

                        if (uploadResponse.code !== 200) {
                            this.$message.error('文件上传失败: ' + (uploadResponse.msg || '未知错误'));
                            return;
                        }
                    } catch (error) {
                        console.error('文件上传错误:', error);
                        this.$message.error('文件上传失败');
                        return;
                    }
                }
            }
            
            request.post('/house/add', this.form2)
            .then(response => {
                const code = response.code;
                if (code === 200) {
                    this.$message.success('添加成功');
                    this.fetchUserInfo();
                    this.load();
                } else {
                    this.$message.error(response.msg || '添加失败，请重试');
                }
            })
            .catch(err => {
                console.error('请求出错:', err);
                this.$message.error('添加失败，请重试');
            });
            
            console.log('提交数据:', JSON.parse(JSON.stringify(this.form2)));
            
            this.resetForm2();
            this.dialogVisible2 = false;
        },
        resetForm1() {
            this.form1.houseId = this.houseId;
            this.form1.landlordId = this.landlordId;
            this.form1.title = this.title,
            this.form1.description = this.description,
            this.form1.price = this.price,
            this.form1.address = this.address,
            this.form1.area = this.area,
            this.form1.size = this.size,
            this.form1.roomCount = this.roomCount,
            this.form1.floor = this.floor,
            this.form1.status = this.status,
            this.form1.imageUrl = this.imageUrl,

            this.disabled = true;
            this.display.display = 'none';

            if (this.$refs.formRef1 && this.$refs.formRef1.resetFields) {
                this.$refs.formRef1.resetFields();
            }
        },
        resetForm2() {
            this.form2.title = "",
            this.form2.description = "",
            this.form2.price = null,
            this.form2.address = "",
            this.form2.area = "",
            this.form2.size = null,
            this.form2.roomCount = null,
            this.form2.floor = null,
            this.form2.imageUrl = "",
            this.form2.fileList = "";

            this.disabled = true;
            this.display.display = 'none';

            if (this.$refs.formRef2 && this.$refs.formRef2.resetFields) {
                this.$refs.formRef2.resetFields();
            }

            this.fileList2 = [];

            if (this.$refs.fileUploadRef) {
                const fileInput = this.$refs.fileUploadRef.$el.querySelector('input[type="file"]');
                if (fileInput) {
                    fileInput.value = '';
                }
            }

            this.selectedFile = null;
        },
        add() {
            this.dialogVisible2 = true;
            this.$nextTick(() => {
                // this.$refs.formRef2.resetFields();
                this.disabled = false;
                // this.form2 = {};
            });
        },
        handleImageChange1(file) {
            const selectedFile = file.raw;

            // 限制图片格式
            const validTypes = ['image/jpeg', 'image/png', 'image/gif'];
            if (!validTypes.includes(selectedFile.type)) {
                this.$message.error('只能上传 JPG、PNG 或 GIF 格式的图片');
                return;
            }

            // 限制图片大小
            const maxSize = 200 * 1024 * 1024;
            if (selectedFile.size > maxSize) {
                this.$message.error('图片大小不能超过 200MB');
                return;
            }

            // 使用 FileReader 读取图片
            const reader = new FileReader();
            reader.onload = (e) => {
                this.form1.imageUrl = e.target.result;
            };
            reader.readAsDataURL(selectedFile);

            this.fileList1 = [file];
        },
        handleImageChange2(file) {
            const selectedFile = file.raw;

            const validTypes = ['image/jpeg', 'image/png', 'image/gif'];
            if (!validTypes.includes(selectedFile.type)) {
                this.$message.error('只能上传 JPG、PNG 或 GIF 格式的图片');
                return;
            }

            const maxSize = 200 * 1024 * 1024;
            if (selectedFile.size > maxSize) {
                this.$message.error('图片大小不能超过 200MB');
                return;
            }

            const reader = new FileReader();
            reader.onload = (e) => {
                this.form2.imageUrl = e.target.result;
            };
            reader.readAsDataURL(selectedFile);

            this.fileList2 = [file];
        },
        handleRemove1() {
            this.fileList1 = [];
            this.form1.imageUrl = '';
            this.$message.success('图片已删除');
        },
        handleRemove2() {
            this.fileList2 = [];
            this.form2.imageUrl = '';
            this.$message.success('图片已删除');
        },  

        // 文件处理
        handleFileChange(file, fileList) {
            const selectedFile = file.raw;
            
            // 验证文件类型
            const validTypes = [
                'application/msword',
                'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                'application/pdf'
            ];
            
            if (!validTypes.includes(selectedFile.type)) {
                this.$message.error('只能上传 doc/docx/pdf 格式的文件');
                return false;
            }
            
            // 验证文件大小（限制大小10MB）
            const maxSize = 10 * 1024 * 1024;
            if (selectedFile.size > maxSize) {
                this.$message.error('文件大小不能超过 10MB');
                return false;
            }
            
            const blobUrl = URL.createObjectURL(selectedFile);
            this.form2.fileList = blobUrl;

            this.selectedFile = selectedFile;
            
            return true;
        },
        
        handleFileRemove() {
            this.form2.fileList = "";
            this.$message.success('文件已删除');
        }
    },
};